import axios from "axios";
import { ElMessageBox, ElMessage } from "element-plus";
import { useAuth } from "@/hooks";
const { getToken, clearToken } = useAuth();
// create an axios instance
const service = axios.create({
    baseURL: `/backapi`,
});
// request interceptor
service.interceptors.request.use(
    (config) => {
        if (getToken()) {
            const token_type = "Bearer";
            config.headers.Authorization = token_type + " " + getToken();
        }
        return config;
    },
    (error) => {
        return Promise.reject(error);
    }
);

service.interceptors.response.use((response: any) => {
    const res = response.data;
    if (res.code !== 20) {
        ElMessage({
            message: res.message || "Error",
            type: "error",
            duration: 5 * 1000,
        });
        if ([1001, 1002, 1003, 1004, 1005].indexOf(response.data.code) != -1) {
            ElMessageBox.confirm(
                "您已经注销，您可以取消停留在本页，或再次登录，确认注销",
                {
                    confirmButtonText: "重新登录",
                    cancelButtonText: "取消",
                    type: "warning",
                }
            ).then(() => {
                clearToken();
                location.reload()
            });
        } else {
            return response;
        }
    } else {
        return response;
    }
});

export default service;
